package com.example.demo.config;

import com.example.demo.datasource.DynamicDataSource;
import com.example.demo.model.TenantInfo;
import com.example.demo.service.ITenantInfoService;
import com.example.demo.utils.SpringContextUtils;
import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ：liushuai
 * @date ：Created in 2020/11/20 15:49
 * @description：${description}
 * @modified By：
 * @version: $version$
 */
@Slf4j
@Component
public class InitDataBaseLink implements ApplicationRunner {

    @Autowired
    private ITenantInfoService tenantInfoService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        DynamicDataSource dynamicDataSource = (DynamicDataSource) SpringContextUtils.getBean("dynamicDataSource");
        HikariDataSource master = (HikariDataSource) SpringContextUtils.getBean("master");
        Map<Object, Object> dataSourceMap = new HashMap<>();
        dataSourceMap.put("master", master);

        List<TenantInfo> tenantList = tenantInfoService.list();
        for (TenantInfo tenantInfos : tenantList) {
            log.info(tenantInfos.getTenantId() + "     " + tenantInfos.getTenantName());
            HikariDataSource dataSource = new HikariDataSource();
            dataSource.setDriverClassName(tenantInfos.getDatasourceDriver());
            dataSource.setJdbcUrl(tenantInfos.getDatasourceUrl());
            dataSource.setUsername(tenantInfos.getDatasourceUsername());
            dataSource.setPassword(tenantInfos.getDatasourcePassword());
            dataSource.setDataSourceProperties(master.getDataSourceProperties());
            dataSourceMap.put(tenantInfos.getTenantId(), dataSource);
        }
        // 设置数据源
        dynamicDataSource.setDataSources(dataSourceMap);
        /**
         * 须执行此操作，才会重新初始化AbstractRoutingDataSource 中的 resolvedDataSources，也只有这样，动态切换才会起效必
         */
        dynamicDataSource.afterPropertiesSet();
    }

}
